package com.thinkit.bigdata.core.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.format.Formatter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * Created by joqk12345 on 9/23/16.
 * www.github.com/joqk12345
 */
public class DateFormatter implements Formatter<Date> {

    @Autowired
    private MessageSource messageSource;

    @Override
    public Date parse(String s, Locale locale) throws ParseException {
        final SimpleDateFormat dateFormat =createDateFormat(locale);
        return dateFormat.parse(s);
    }

    @Override
    public String print(Date date, Locale locale) {
        final SimpleDateFormat dateFormat =createDateFormat(locale);
        return dateFormat.format(date);
    }

    private SimpleDateFormat createDateFormat(final Locale local){
        final  String format = this.messageSource.getMessage("date.format",null,local);
        final  SimpleDateFormat dateFormat = new SimpleDateFormat(format);
//        System.out.println("entert this formatter ");
        dateFormat.setLenient(false);
        return  dateFormat;
    }
}
